/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lanchat.model.net;

import com.lanchat.model.data.User;
import com.lanchat.model.util.ChatByteArrayOutputStream;
import com.lanchat.model.util.LocalIPGetter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 广播信息类
 * 
 * @author zhangzhe
 */
public class Broadcaster {

    private InetAddress group = null;
    private MulticastSocket socket = null;

    /**
     * 
     */
    public Broadcaster() {
        try {
            BroadcastAddr info = new BroadcastAddr();
            info.setNetaddr(LocalIPGetter.getMyIP());
            info.setNetmask("255.255.0.0");
            info.execCalc();
//            System.out.println(info.getNetbroadcastaddr());            
            group = InetAddress.getByName(info.getNetbroadcastaddr());
            socket = new MulticastSocket(NetConstant.BROADCAST_PORT);
            socket.setTimeToLive(NetConstant.BROADCAST_TIMETOLIVE);
            socket.joinGroup(group);
        } catch (IOException ex) {
            Logger.getLogger(Broadcaster.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void send(Object data) throws IOException {
        ChatByteArrayOutputStream bout = new ChatByteArrayOutputStream(
                NetConstant.DATAGRAMPACKET_SIZE);
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(data);
        out.flush();
        DatagramPacket packet = new DatagramPacket(bout.getBuf(), bout.size(),
                group, NetConstant.BROADCAST_PORT);
        socket.send(packet);
    }

    public void dispose() {
        group = null;
        socket.close();
        socket = null;
    }
}
